//
//  BlogChoiceViewController.m
//  iFlick
//
//  Created by 张 霄鹤 on 09-9-25.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "BlogChoiceViewController.h"
#import "ViewControllerChooser.h"
#import "WebAuthorizeViewController.h"


@implementation BlogChoiceViewController

@synthesize delegate = _delegate;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.title = NSLocalizedStringFromTable(@"YOUR_BLOGS",@"main",@"");

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	blogs = [[NSMutableArray alloc] init];
	currentSelect = -1;
	
	UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(startLoadThread:)];
	self.navigationItem.rightBarButtonItem = refresh;
	[self startLoadThread:self];
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	currentSelect = -1;
}

/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	if(loadBlogListThread){
		if([loadBlogListThread isExecuting]){
			[loadBlogListThread cancel];
			canceled = YES;
			isLoading = NO;
		}
	}
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;  // 0: add;  1: blogs
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger con = 0;
	if(section == 0){
		con = 1;
	}else if(section == 1){
		con = [blogs count];
	}
	return con;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	NSInteger section = indexPath.section;
	
    if (cell == nil) {
		if(section == 1){
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		}else{
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		}
    }
	
	if(section == 0){
		NSString *title;
		if([blogs count] > 0){
			title = NSLocalizedStringFromTable(@"ADD_BLOG",@"main",@"");
		}else{
			title = NSLocalizedStringFromTable(@"NO_ADD_BLOG",@"main",@"");
		}
		cell.textLabel.text = title;
	}else if(section == 1){
		NSString *ctitle;
		NSString *cdesc;
		NSInteger row = indexPath.row;
		NSInteger bs = [blogs count];
		if(bs > 0){
			BlogInfo *blogInfo = [blogs objectAtIndex:row];
			ctitle = blogInfo.blogName;
			cdesc = blogInfo.blogURL;
			// 3.0 版本设置样式
			cell.textLabel.text = ctitle;
			cell.detailTextLabel.text = cdesc;
			if(row == currentSelect){
				cell.accessoryType = UITableViewCellAccessoryCheckmark;
			}else {
				cell.accessoryType = UITableViewCellAccessoryNone;
			}
		}
	}
	
    
    // Set up the cell...
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	NSInteger section = indexPath.section;
	if(section == 0){
		// TODO 添加blog
		//      flickr.com 添加的地址为 http://www.flickr.com/blogs_add.gne
		// [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.flickr.com/blogs_add.gne"]];
		WebAuthorizeViewController *wac = (WebAuthorizeViewController *)[[ViewControllerChooser sharedChooser] choose:VCC_ID_WEB];
		wac.delegate = self;
		wac.url = [NSURL URLWithString:@"http://www.flickr.com/blogs_add.gne"];
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		[self.navigationController pushViewController:wac animated:YES];
		wac.navigationItem.title = @"Add Blog";		
	}else if(section == 1){
		currentSelect = indexPath.row;
		UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		if(_delegate){
			BlogInfo *blogInfo = (BlogInfo *)[blogs objectAtIndex:indexPath.row];
			BOOL needPW = blogInfo.needPassword;
			if(needPW){
				if(alert == nil){
					alert = [[UIAlertView alloc] init];
					[alert setDelegate:self];
					[alert setTitle:@"Enter Password"];
					[alert setMessage:@" "];
					[alert addButtonWithTitle:@"Cancel"];
					[alert addButtonWithTitle:@"OK"];
				}
				[alert show];
			}else{
				id ret = [_delegate selected:blogInfo];
				if(ret){
					if([ret isKindOfClass:[NSError class]]){
						NSError *err = (NSError *)ret;
						UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"Error" message:[err localizedDescription] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
						[alt show];
						[alt release];
					}else{
						cell.accessoryType = UITableViewCellAccessoryCheckmark;
						[self.navigationController popViewControllerAnimated:YES];
					}
				}
			}
		}else{
			[self.navigationController popViewControllerAnimated:YES];
		}
	}
}

/**
 * 获取指定section的标题
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSString *ret = nil;
	switch (section) {
		case 0:
			ret = [NSString stringWithString:(NSLocalizedStringFromTable(@"ADD_BLOG",@"main",@""))];
			break;
		case 1:
			ret = [NSString stringWithString:(NSLocalizedStringFromTable(@"YOUR_BLOGS",@"main",@""))];
			break;
			
		default:
			break;
	}
	return ret;
}

#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)willPresentAlertView:(UIAlertView *)alertView{
	if(txtPassword == nil){
		NSInteger w = alertView.frame.size.width;
		NSInteger h = alertView.frame.size.height;
		NSInteger pw = w - 40;
		NSInteger ph = (h - 40)/2;
		txtPassword = [[[UITextField alloc] initWithFrame:CGRectMake(20, ph, pw, 20)] autorelease];
		txtPassword.backgroundColor = [UIColor whiteColor];
		txtPassword.placeholder = @"Password";
		txtPassword.delegate = self;
		txtPassword.secureTextEntry = YES;
		[alertView addSubview:txtPassword];
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 1){
		NSString *pwd = txtPassword.text;
		if(pwd){
			if([pwd length] > 0){
				BlogInfo *blog = (BlogInfo *)[blogs objectAtIndex:currentSelect];
				blog.password = pwd;
				[NSThread detachNewThreadSelector:@selector(postPhoto:) toTarget:self withObject:blog];
			}
		}
	}
}

#pragma mark -
#pragma mark ThreadFunction
/**
 * 线程执行操作，执行图像发布
 */
- (void)postPhoto:(id)param{
	[_delegate selected:((BlogInfo *)param)];
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	return [textField resignFirstResponder];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark WebAuthorizeViewControllerDelegate
- (void)continueWork:(id)sender{
	[self.navigationController popViewControllerAnimated:YES];
}

/**
 * 开始Blog加载线程
 */
- (void)startLoadThread:(id)sender{
//	if(active == nil){
//		active = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//	}
//	UIBarButtonItem *bar = [[[UIBarButtonItem alloc] initWithCustomView:active] autorelease];
//	[self.navigationItem setRightBarButtonItem:bar animated:YES];
//	[active startAnimating];
	
	//DataManager *dm = [DataManager sharedDataManager];
	
	if(loadBlogListThread){
		if([loadBlogListThread isExecuting]){
			return;
		}
		[loadBlogListThread release];
	}
	loadBlogListThread = [[NSThread alloc] initWithTarget:self selector:@selector(loadBlogList:) object:nil];
	[loadBlogListThread start];
	canceled = NO;
}

/**
 * 实际的装载博客列表操作
 */
- (void)loadBlogList:(id)sender{
	if(!isLoading){
		isLoading = YES;
		DataManager *dm = [DataManager sharedDataManager];
		id obj = [dm getBlogListFromServer];
		if(canceled){
			isLoading = NO;
			return;
		}
		if([obj isKindOfClass:[NSArray class]]){
			NSArray *list = (NSArray *)obj;
			int con = [list count];
			if(con > 0){
				[blogs setArray:list];
				[table reloadData];
			}else{
				// TODO 显示无blog
			}
		}else if([obj isKindOfClass:[NSError class]]){
			NSError *err = (NSError *)obj;
			UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"Error" message:[err localizedDescription] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
			[al show];
			[al release];
		}
		isLoading = NO;
//		[active stopAnimating];
//		[active removeFromSuperview];
	}
}


- (void)dealloc {
	[blogs release];
	if(loadBlogListThread){
		if([loadBlogListThread isExecuting]){
			[loadBlogListThread cancel];
			canceled = YES;
		}
		[loadBlogListThread release];
	}
//	if(active){
//		[active release];
//	}
    [super dealloc];
}


@end

